<!-- apk 管理 -->
<template>
  <div class="apkupdate">
    <CustomTree title="apk类型" width="160rem" selectFirstNode api="/znjszd3/comm/getDictCodeList" :params="{ dicttype: 'CNP_APKTYPE' }" @leaf-node-click="handleTreeClick"></CustomTree>
    <div class="table-box" v-loading="tableLoading">
      <CustomTable
        ref="tableRef"
        type="selection"
        :requestImmediate="false"
        multiple
        v-model:selection="apkSelections"
        v-model:form="searchForm"
        :tableHeader="params.apktype == 'biess' ? biessTableHeader : tableHeader"
        lastColMinWidth="10%"
        api="/znjszd3/ht/apkCnp/getApkCnpList"
        :params="params"
      >
        <template v-slot:tableTop="{ rows }">
          <el-button type="primary" class="add" plain @click="addDialogVisible = true"
            ><el-icon><Plus /></el-icon>新增</el-button
          >
          <el-button type="primary" class="add" plain @click="refresh">
            <el-icon><Refresh /></el-icon>
            发布终端APK</el-button
          >
        </template>
        <template v-if="params.apktype == 'biess'" v-slot:ICONURL="{ row }">
          <img :src="row.ICONURL + '?token=' + userStore.token" style="width: 40rem; margin-top: 3rem" />
        </template>
        <template v-slot:lastColumn="{ row }">
          <!-- <el-button type="primary" plain @click.stop="view(row)"
            ><el-icon><View /></el-icon>查看</el-button
          > -->
          <el-button type="danger" plain @click.stop="del(row.ID)"
            ><el-icon><Delete /></el-icon>删除</el-button
          >
        </template>
      </CustomTable>
    </div>
    <CustomDialog v-if="params.apktype" title="新增APK" v-model:dialogVisible="addDialogVisible" width="30%" :height="params.apktype == 'biess' ? '515rem' : '320rem'" top="20vh" @confirm="addApk" @handleClose="handleAddClose">
      <!-- <CustomForm ref="formRef" v-model:form="addForm" :editable="true" columns="1"> </CustomForm> -->

      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="auto" class="demo-ruleForm add-form" status-icon>
        <el-form-item label="APK名称" prop="apkName">
          <el-input v-model="addForm.apkName" placeholder="请输入APK名称" />
        </el-form-item>
        <el-form-item label="开发公司" prop="kffactory">
          <el-select v-model="addForm.kffactory" placeholder="请选择开发公司" @click="getCompany">
            <el-option v-for="(item, index) in company" :label="item.zdzw" :value="item.zddm" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="params.apktype == 'biess'" label="APK模式" prop="apkymlx">
          <el-select v-model="addForm.apkymlx" placeholder="请选择APK模式" @click="getApkModule">
            <el-option v-for="(item, index) in apkModule" :label="item.zdzw" :value="item.zddm" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="params.apktype == 'biess' && addForm.apkymlx == 'androidweb'" label="嵌套地址" prop="weburl">
          <el-tree-select node-key="zddm" v-model="addForm.weburl" :data="webUrl" :render-after-expand="false" :props="{ label: 'zdzw', value: 'zddm' }" show-checkbox @click="getWebUrl" />
        </el-form-item>
        <el-form-item label="APK文件" prop="fileName">
          <input type="file" ref="fileUploadRef" multiple style="display: none" @input="onFileChange($event)" />
          <el-input v-model="addForm.fileName" />
          <el-button type="primary" class="add" plain @click="fileUploadRef.click()"
            ><el-icon><UploadFilled /></el-icon>选择文件</el-button
          >
        </el-form-item>
        <el-form-item v-if="params.apktype == 'biess'" label="APK图标" class="apkIcon-form-item" prop="iconid">
          <img :src="selectedIcon.iconurl || no_image" class="apk-img" />
          <el-button type="primary" plain @click="selectIcon"
            ><el-icon><PictureFilled /></el-icon>选择图标</el-button
          >
        </el-form-item>
      </el-form>
    </CustomDialog>
    <CustomDialog title="请选择监室" v-model:dialogVisible="dialogVisible" width="30%" height="600rem" top="20vh" @confirm="confirm">
      <el-tree v-loading="jshTree.length == 0" icon="icon-anzhuo" style="max-width: 600rem" class="jsh-tree" node-key="zddm" :props="jshTreeProps" :data="jshTree" show-checkbox @check="handleJshChange" />
    </CustomDialog>
    <CustomDialog title="APK更新进度" v-model:dialogVisible="statusDialogVisible" width="30%" height="600rem" top="20vh" @confirm="statusDialogVisible = false">
      <el-scrollbar height="450rem">
        <el-collapse v-model="activeNames">
          <el-collapse-item v-for="item in jshSelections" :key="item.zddm" :name="item.zddm">
            <template #title>
              {{ item.zdzw }} &nbsp;&nbsp;
              <template v-if="item.children.some((apk) => apk.updated !== true)">
                {{ item.msg }}
                <el-icon class="apk-uploading" size="20"><Loading /></el-icon>
              </template>
              <template v-if="!item.children.some((apk) => apk.updated === false) && item.msg != '卸载成功'">更新成功<el-result icon="success"> </el-result></template>
              <template v-if="item.msg == '卸载成功'">{{ item.msg }}<el-result icon="success"> </el-result></template>
            </template>
            <!-- <template #title>
              {{ item.zdzw }} &nbsp;&nbsp;
              <template v-if="item.doWhat == 'cnpUpdateApking' && item.children.every((apk) => apk.updated !== true)">
                {{ item.msg }} <el-icon class="apk-uploading" size="20"><Loading /></el-icon>
              </template>
              <template v-if="item.children.every((apk) => apk.updated === true)">{{ item.msg }}<el-result icon="success"> </el-result></template>
            </template> -->
            <div class="apk-name" v-for="apk in item.children" :key="apk.ID">
              <i class="iconfont icon-anzhuo"></i> {{ apk.APKNAME }}
              <el-icon v-if="item.doWhat == 'cnpUpdateApking' && apk.updated !== true" class="apk-uploading" size="16"><Loading /></el-icon>
              <template v-if="apk.updated === true">
                <span v-if="apk.msg == '已是最新版本，无需更新'">&nbsp;&nbsp; ({{ apk.msg }})</span>
                <template v-else>
                  {{ apk.msg }}
                  <el-result icon="success"> </el-result>
                </template>
              </template>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-scrollbar>
    </CustomDialog>
    <CustomDialog title="请选择APK图标" width="50%" height="780rem" v-model:dialogVisible="iconDialogVisible" @confirm="closeIconDialog">
      <div class="icon-warp" v-loading="iconsLoading">
        <el-scrollbar height="600rem">
          <div class="icon-box">
            <div class="icom-item" v-for="item in apkIcons" :key="item.iconurl" @click="selectIconItem(item)">
              <img :src="item.iconurl + '?token=' + userStore.token" />
              <label v-if="item.selected" class="selected-label flex-center"
                ><el-icon color="#fff"><Select /></el-icon
              ></label>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </CustomDialog>
    <CustomDialog title="APK详情" width="50%" height="320rem" v-model:dialogVisible="detailDialogVisible">
      <CustomForm v-model:form="detailForm" labelWidth="140rem" columns="2"></CustomForm>
    </CustomDialog>
    <!-- <div class="msg">
      {{ msg }}
    </div> -->
  </div>
</template>

<script setup name="apkupdate">
import { ref, onMounted, computed, watch, onBeforeUnmount, nextTick } from 'vue'
import { http, uploadFile, fillData } from '@/utils/index.js'
import { stores } from '@/stores/index.js'
import Stomp from 'stompjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import no_image from '../../assets/image/no_image.png'
import { useWebsocket } from '@/composables/websocket.js'
const tableRef = ref()
const addFormRef = ref()
const formRef = ref()
const userStore = stores.useUserStore()
const props = defineProps({})
//当前业务类型
const currentTyep = ref('')
const activeNames = ref('') //激活的collapse面板
// const apkname = ref('')
const loading = ref(false)
const tableLoading = ref(false)
const updateApkLoading = ref(false)
const iconsLoading = ref(false)
const dialogVisible = ref(false)
const addDialogVisible = ref(false)
const statusDialogVisible = ref(false) //APK更新进度弹框
const iconDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedFile = ref({})
const selectedIcon = ref({})
const apkIcons = ref([])
//请求table或请求socket数据所需的参数
const params = ref({
  apktype: ''
})
const { socketData } = useWebsocket('/znjszd3/ht/apkCnp/getWsForUpdateCnpApk', 'get', params)

watch(socketData, (newVal) => {
  console.log(newVal)
  //推送的是终端是否开始更新apk
  if (newVal.doWhat == 'cnpUpdateApking') {
    let room = jshSelections.value.find((item) => item.zddm == newVal.jsh)
    room.msg = newVal.msg
    room.doWhat = newVal.doWhat
  } //推送的是某个终端某个apk更新状态信息
  else if (newVal.doWhat == 'cnpUpdateApkFinish') {
    let room = jshSelections.value.find((item) => item.zddm == newVal.data.jsh)
    //卸载终端全部apk 完成
    if (newVal.data.msg == '卸载成功') {
      room.msg = newVal.data.msg
    } else {
      // 更新某个apk
      room.children.find((apk) => {
        if (apk.ID == newVal.data.id) {
          apk.msg = newVal.data.msg
          apk.doWhat = newVal.doWhat
          if (newVal.data.status == 200) {
            apk.updated = true
          }
          return
        }
      })
    }
  }
})
const addForm = ref({
  apkName: '',
  kffactory: '',
  apkymlx: '',
  weburl: '',
  fileName: '',
  iconid: ''
})
const detailForm = ref({
  APKNAME: '',
  FILENAME: '',
  PACKAGENAME: '',
  APKTYPEMC: '',
  KFFACTORYMC: '',
  COMPANYMC: '',
  YWFZMC: '',
  // YWFZMC: null,
  VERSION: '',
  ADDTIME: '',
  ICONURL: ''
})
const rules = ref({
  apkName: [{ required: true, message: '请输入APK名称', trigger: 'blur' }],
  kffactory: [{ required: true, message: '请选择开发公司', trigger: 'blur' }],
  apkymlx: [{ required: true, message: '请选择APK模式', trigger: 'blur' }],
  weburl: [{ required: true, message: '请选择嵌套地址', trigger: 'blur' }],
  fileName: [{ required: true, message: '请选择APK文件', trigger: 'change' }],
  iconid: [{ required: true, message: '请选择图标文件', trigger: 'change' }]
})

const jshTree = ref([])
const jshSelections = ref([])
const apkSelections = ref([])
const fileUploadRef = ref()
const fileList = ref([])
const apkTreeProps = {
  children: 'children',
  label: 'zdzw'
}
const jshTreeProps = {
  children: 'children',
  label: 'zdzw'
}

const tableHeader = ref([
  {
    key: 'APKNAME',
    label: '名称',
    width: '8%'
  },
  {
    key: 'FILENAME',
    label: '文件名称',
    width: '23%'
  },
  {
    key: 'PACKAGENAME',
    label: '包名',
    width: '20%'
  },
  {
    key: 'APKTYPEMC',
    label: '类型',
    width: '8%'
  },
  {
    key: 'KFFACTORYMC',
    label: 'APK开发公司 ',
    width: '10%'
  },
  // {
  //   key: 'apkymlx',
  //   label: 'APK模式',
  //   width: '8%'
  // },
  {
    key: 'COMPANYMC',
    label: 'APK适合终端',
    width: '10%'
  },

  {
    key: 'VERSION',
    label: '版本号',
    width: '7%'
  },
  {
    key: 'ADDTIME',
    label: '上传时间',
    width: '13%',
    sortable: 'custom'
  }
])
//业务apk
const biessTableHeader = ref([
  {
    key: 'APKNAME',
    label: '名称',
    width: '12%'
  },
  {
    key: 'YWFZMC',
    label: '业务分组',
    width: '11%'
  },

  {
    key: 'APKTYPEMC',
    label: '类型',
    width: '10%'
  },
  {
    key: 'KFFACTORYMC',
    label: 'APK开发公司 ',
    width: '10%'
  },
  {
    key: 'ICONURL',
    label: 'APK图标',
    width: '8%'
  },
  {
    key: 'COMPANYMC',
    label: 'APK适合终端',
    width: '10%'
  },

  {
    key: 'VERSION',
    label: '版本号',
    width: '7%'
  },
  {
    key: 'ADDTIME',
    label: '上传时间',
    width: '18%',
    sortable: 'custom'
  }
])
const searchForm = ref({
  apkname: '',
  filename: ''
})
const company = ref([])
const apkModule = ref([])
const webUrl = ref([])
const allDone = computed(() => {
  return item.children.some((apk) => apk.updated !== true)
})
watch(
  () => params,
  (newVal) => {
    console.log(newVal.value.apktype)
    if (newVal.value.apktype == 'biess') {
      console.log(111)
      detailForm.value.YWFZMC = ''
      detailForm.value.ICONURL = ''
    } else {
      console.log(2222)
      detailForm.value.YWFZMC = null
      detailForm.value.ICONURL = null
    }
  },
  { deep: true }
)
onBeforeUnmount(() => {})
onMounted(async () => {})

//获取开发公司
const getCompany = () => {
  http('/znjszd3/comm/getDictCodeList', 'get', {
    dicttype: 'CNP_COMPANY'
  }).then((res) => {
    company.value = res.data
  })
}
//获取APK模式
const getApkModule = () => {
  http('/znjszd3/comm/getDictCodeList', 'get', {
    dicttype: 'ZDAPK_YMLX'
  }).then((res) => {
    apkModule.value = res.data
  })
}
//获取安卓嵌套web地址
const getWebUrl = () => {
  http('/znjszd3/comm/tree/getDwConfigTreeGroupDwdm', 'get', {
    forapp: '9997'
  }).then((res) => {
    webUrl.value = res.data
  })
}
//点击选择APK图标按钮
const selectIcon = () => {
  iconDialogVisible.value = true
  iconsLoading.value = true
  http('/znjszd3/ht/apkCnp/getApkIconList', 'get')
    .then((res) => {
      console.log(res)
      apkIcons.value = res.data
    })
    .finally(() => {
      iconsLoading.value = false
    })
}
//选择icon图标
const selectIconItem = (item) => {
  apkIcons.value.forEach((x) => (x.selected = false))
  item.selected = !item.selected
}
const closeIconDialog = () => {
  selectedIcon.value = apkIcons.value.find((item) => item.selected) || {}
  if (Object.keys(selectedIcon.value).length == 0) return ElMessage.warning('请先选择图标')
  iconDialogVisible.value = false
  addForm.value.iconid = selectedIcon.value.id
}

const handleTreeClick = (node) => {
  console.log(node)
  params.value.apktype = node.zddm
  apkSelections.value = []
  tableRef.value.getData()
}
const addApk = (obj) => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      const formData = new FormData()
      formData.append('apkFile', selectedFile.value)
      formData.append('apktype', params.value.apktype)
      formData.append('apkname', addForm.value.apkName)
      formData.append('kffactory', addForm.value.kffactory)
      if (params.value.apktype == 'biess') {
        formData.append('apkymlx', addForm.value.apkymlx)
        formData.append('weburl', addForm.value.weburl)
        formData.append('iconid', selectedIcon.value.id)
      }

      tableLoading.value = true

      uploadFile('/znjszd3/ht/apkCnp/addApkCnp', formData)
        .then((res) => {
          if (res.status == 200) {
            tableRef.value.getData()
            ElMessage.success(res.message[0])
            addDialogVisible.value = false
            addForm.value = {}
            selectedIcon.value = {}
          }
        })
        .finally(() => {
          tableLoading.value = false
        })
    }
  })
}
//选择上传文件后的回调函数
const onFileChange = (event) => {
  const file = event.target.files[0]
  selectedFile.value = file
  if (!file.name.toLowerCase().includes('.apk') || !file.name.toUpperCase().includes('.APK')) {
    event.target.value = ''
    return ElMessage.error('请选择正确的文件类型')
  }
  addForm.value.fileName = file.name
  event.target.value = ''
}
const handleAddClose = () => {
  addForm.value = {}
}

const getJsh = () => {
  http('/znjszd3/comm/tree/getTreeDwdmJsh', 'get').then((res) => {
    jshTree.value = res.data
  })
}
//选择监室
const handleJshChange = (node, nodes) => {
  jshSelections.value = nodes.checkedNodes
}

//同步终端数据
const refresh = (rows) => {
  if (apkSelections.value.length == 0) {
    ElMessageBox.confirm('此操作将会卸载终端所有APK应用,确定要卸载吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      dialogVisible.value = true
      getJsh()
    })
    // .catch(() => {})
  } else {
    dialogVisible.value = true
    getJsh()
  }
}
//选择监室后开始更新APK
const confirm = () => {
  const ids = apkSelections.value.map((item) => item.ID)
  const jshList = jshSelections.value.map((item) => {
    return {
      jsh: item.zddm,
      dwdm: item.dwdm
    }
  })

  http(
    '/znjszd3/ht/apkCnp/updateCnpApk',
    'post',
    {
      ids: ids.join(),
      apkType: params.value.apktype,
      jshList: jshList
    },
    false
  ).then((res) => {
    if (res.status == 200) {
      ElMessage.success(res.message[0])
      //显示apk更新进度
      jshSelections.value = jshSelections.value.map((item) => {
        return {
          ...item,
          children: JSON.parse(JSON.stringify(apkSelections.value))
        }
      })
      jshSelections.value.forEach((item) => {
        item.children.forEach((x) => {
          x.updated = false
        })
      })
      dialogVisible.value = false
      statusDialogVisible.value = true
    }
  })
}
const view = (row) => {
  detailDialogVisible.value = true
  fillData(detailForm.value, row)
}

//
const del = (id) => {
  ElMessageBox.confirm('确定要删除该APK吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableLoading.value = true
    http(
      '/znjszd3/ht/apkCnp/delApkCnp',
      'post',
      {
        id: id
      },
      false
    )
      .then((res) => {
        if (res.status == 200) {
          tableRef.value.getData()
          ElMessage.success(res.message[0])
        }
      })
      .finally(() => {
        tableLoading.value = false
      })
  })
}
</script>

<style lang="scss" scoped>
.apkupdate {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;

  .table-box {
    margin: 10px 10px 0;
    width: calc(100% - 160px);
    height: 965px;
    ::v-deep(.custom-table) {
      .add {
        .el-icon {
          font-size: 18px !important;
        }
      }
    }
  }
  .custom-table {
  }
}
::v-deep(.custom-dialog) {
  .add-form {
    margin-bottom: 30px;
    .apkIcon-form-item {
      .el-form-item__label-wrap {
        align-items: center;
      }
    }
    .el-input,
    .el-select,
    .el-tree-select {
      margin-right: 15px;
      width: 380px;
    }
  }

  .jsh-tree {
    margin-bottom: 30px;
    height: 420px;
    overflow: auto;
    .el-tree-node__label {
      font-size: 18px;
      font-family: 'open sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }
    .el-checkbox__inner {
      height: 18px;
      width: 18px;
      &::after {
        height: 8px;
        left: 6px;
        top: 3px;
      }
    }
    .el-checkbox__input.is-indeterminate .el-checkbox__inner:before {
      top: 7px;
    }
  }
  .el-collapse {
    .el-collapse-item__header {
      font-size: 16px !important;
    }
    .el-collapse-item__content {
      padding-bottom: 10px;
    }
    .el-result {
      margin-left: 5px;
      padding: 0;
      .el-result__icon {
        display: flex;
        justify-content: center;
        align-items: center;
        svg {
          width: 25px;
          height: 25px;
        }
      }
    }
    .apk-name {
      height: 30px;
      display: flex;
      align-items: center;
      font-size: 14px;
      padding-left: 15px;
      .icon-anzhuo {
        margin-right: 5px;
        color: var(--el-color-primary);
        font-size: 20px;
      }
      .el-result__icon {
        svg {
          width: 18px;
          height: 18px;
        }
      }
    }
    .apk-uploading {
      margin-left: 10px;
      color: var(--el-color-primary);
      animation: rotate 2s linear infinite;
    }
  }
  .apk-img {
    margin-right: 20px;
    width: 80px;
    // border: 1px solid blueviolet;
    border-radius: 10px;
  }
  .icon-warp {
    border: var(--el-border);
    padding: 10px;
    border-radius: 6px;
  }
  .icon-box {
    // padding: 10px;
    margin-right: 15px;

    display: grid;
    grid-template-columns: repeat(10, 1fr);

    gap: 10px;

    .icom-item {
      position: relative;
      height: 88px;
      cursor: pointer;
      border-radius: 10px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
      }
    }
    .selected-label {
      position: absolute;
      right: -18px;
      top: -10px;
      width: 50px;
      height: 30px;
      background: #67c23a;
      text-align: center;
      transform: rotate(45deg);
      .el-icon {
        font-size: 14px;
        margin-top: 11px;
        transform: rotate(-45deg);
      }
    }
  }
}
.msg {
  position: absolute;
  width: 600px;
  height: 200px;
  border: 1px solid red;
  top: 60px;
  right: 10px;
  z-index: 99999;
}
</style>
